<script setup lang="ts">
import { ref, computed } from 'vue'
import { message, Modal } from 'ant-design-vue'
import {
  FileTextOutlined,
  PlusOutlined,
  CheckOutlined,
  CloseOutlined,
} from '@ant-design/icons-vue'
import { useWallet } from '../../../composables/useWallet'

const {
  isConnected,
  isReady,
  currentAccount,
  getContract,
} = useWallet()

// 提案表单
const proposalForm = ref({
  familyId: '',
  title: '',
  description: '',
  proposalType: 'general',
})

// 提案列表
const proposalList = ref<any[]>([])

// 加载状态
const isCreatingProposal = ref(false)
const isVoting = ref(false)
const isLoadingProposals = ref(false)

// 模态框
const createProposalModalVisible = ref(false)

// 提案类型
const proposalTypes = [
  { label: '常规提案', value: 'general' },
  { label: '财务提案', value: 'financial' },
  { label: '成员提案', value: 'member' },
  { label: '治理提案', value: 'governance' },
]

/**
 * 创建提案
 */
async function createProposal() {
  if (!isReady.value) {
    message.error('请先连接钱包')
    return
  }

  if (!proposalForm.value.familyId || !proposalForm.value.title) {
    message.error('请填写完整信息')
    return
  }

  isCreatingProposal.value = true

  try {
    console.log('📝 创建提案...')
    
    // 将proposalType映射为数字
    const typeMap: Record<string, number> = {
      'general': 0,
      'financial': 1,
      'member': 2,
      'governance': 3
    }
    
    // 调用后端 API 创建提案
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'}/blockchain/governance/proposal`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        familyId: parseInt(proposalForm.value.familyId),
        title: proposalForm.value.title,
        description: proposalForm.value.description,
        proposalType: typeMap[proposalForm.value.proposalType] || 0,
        executionData: []
      })
    })
    
    const result = await response.json()
    
    if (result.code !== 200) {
      throw new Error(result.message || '创建提案失败')
    }
    
    console.log('✅ 提案创建成功！交易哈希:', result.data.txHash)
    
    message.success(`提案 "${proposalForm.value.title}" 创建成功！`)
    
    // 重置表单
    proposalForm.value = {
      familyId: '',
      title: '',
      description: '',
      proposalType: 'general',
    }
    
    createProposalModalVisible.value = false
    
    // 刷新提案列表
    await loadProposals(proposalForm.value.familyId)
    
  } catch (error: any) {
    console.error('❌ 创建提案失败:', error)
    
    if (error.code === 4001) {
      message.error('用户取消了交易')
    } else if (error.message?.includes('not member')) {
      message.error('只有家族成员才能创建提案')
    } else {
      message.error(`创建失败: ${error.message || '未知错误'}`)
    }
  } finally {
    isCreatingProposal.value = false
  }
}

/**
 * 投票
 */
async function vote(proposalId: string, support: boolean) {
  if (!isReady.value) return

  isVoting.value = true

  try {
    console.log(`🗳️ 投票: ${support ? '赞成' : '反对'}`)
    
    // 调用后端 API 投票
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'}/blockchain/governance/vote`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        proposalId: parseInt(proposalId),
        support: support,
        reason: ''
      })
    })
    
    const result = await response.json()
    
    if (result.code !== 200) {
      throw new Error(result.message || '投票失败')
    }
    
    console.log('✅ 投票成功！交易哈希:', result.data.txHash)
    
    message.success(`投票${support ? '赞成' : '反对'}成功！`)
    
    // 刷新提案详情
    await loadProposals('')
    
  } catch (error: any) {
    console.error('❌ 投票失败:', error)
    
    if (error.code === 4001) {
      message.error('用户取消了交易')
    } else if (error.message?.includes('already voted')) {
      message.error('您已经投过票了')
    } else if (error.message?.includes('not member')) {
      message.error('只有家族成员才能投票')
    } else {
      message.error(`投票失败: ${error.message || '未知错误'}`)
    }
  } finally {
    isVoting.value = false
  }
}

/**
 * 加载提案列表
 */
async function loadProposals(familyId: string) {
  if (!isReady.value) return

  isLoadingProposals.value = true

  try {
    console.log('📋 加载提案列表...')
    
    // 调用后端 API 获取提案列表
    const url = familyId 
      ? `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'}/blockchain/governance/proposals?familyId=${familyId}`
      : `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'}/blockchain/governance/proposals`
    
    const response = await fetch(url)
    const result = await response.json()
    
    if (result.code === 200) {
      proposalList.value = result.data || []
      console.log('✅ 提案列表加载完成:', proposalList.value.length)
    } else {
      throw new Error(result.message || '加载提案列表失败')
    }
    
  } catch (error: any) {
    console.error('❌ 加载提案列表失败:', error)
    message.error(`加载提案列表失败: ${error.message || '未知错误'}`)
  } finally {
    isLoadingProposals.value = false
  }
}

/**
 * 确认投票
 */
function confirmVote(proposal: any, support: boolean) {
  Modal.confirm({
    title: `确认投${support ? '赞成' : '反对'}票？`,
    content: `提案: ${proposal.title}`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      await vote(proposal.id, support)
    },
  })
}

/**
 * 格式化地址
 */
function formatAddress(address: string) {
  if (!address) return '-'
  return `${address.slice(0, 6)}...${address.slice(-4)}`
}

/**
 * 格式化时间
 */
function formatTimestamp(timestamp: number) {
  if (!timestamp) return '-'
  return new Date(timestamp * 1000).toLocaleString('zh-CN')
}

/**
 * 获取状态标签颜色
 */
function getStatusColor(status: string) {
  const colors: Record<string, string> = {
    pending: 'processing',
    passed: 'success',
    rejected: 'error',
    executed: 'default',
  }
  return colors[status] || 'default'
}

/**
 * 获取状态名称
 */
function getStatusName(status: string) {
  const names: Record<string, string> = {
    pending: '投票中',
    passed: '已通过',
    rejected: '已拒绝',
    executed: '已执行',
  }
  return names[status] || status
}

/**
 * 计算投票进度
 */
function getVoteProgress(proposal: any) {
  const total = proposal.votesFor + proposal.votesAgainst
  if (total === 0) return 0
  return Math.round((proposal.votesFor / total) * 100)
}
</script>

<template>
  <div class="governance">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h2><FileTextOutlined /> 治理提案</h2>
        <p>创建和投票家族治理提案</p>
      </div>
      <a-button
        v-if="isConnected"
        type="primary"
        size="large"
        @click="createProposalModalVisible = true"
      >
        <PlusOutlined /> 创建提案
      </a-button>
    </div>

    <!-- 未连接钱包提示 -->
    <a-alert
      v-if="!isConnected"
      type="warning"
      message="请先连接钱包"
      description="您需要连接 MetaMask 钱包才能创建和投票提案"
      show-icon
      style="margin-bottom: 24px"
    />

    <!-- 提案列表 -->
    <a-card v-else title="提案列表" style="margin-top: 24px">
      <a-spin :spinning="isLoadingProposals" tip="加载中...">
        <a-empty
          v-if="proposalList.length === 0"
          description="还没有提案"
        >
          <a-button type="primary" @click="createProposalModalVisible = true">
            <PlusOutlined /> 创建第一个提案
          </a-button>
        </a-empty>

        <a-list
          v-else
          :data-source="proposalList"
          :pagination="{ pageSize: 10 }"
        >
          <template #renderItem="{ item }">
            <a-list-item>
              <a-card hoverable style="width: 100%">
                <template #title>
                  <div style="display: flex; align-items: center; justify-content: space-between">
                    <span>{{ item.title }}</span>
                    <a-tag :color="getStatusColor(item.status)">
                      {{ getStatusName(item.status) }}
                    </a-tag>
                  </div>
                </template>
                
                <p>{{ item.description }}</p>
                
                <a-row :gutter="16" style="margin-top: 16px">
                  <a-col :span="12">
                    <div class="proposal-info">
                      <span class="label">提案人:</span>
                      <a-tag color="blue">{{ formatAddress(item.proposer) }}</a-tag>
                    </div>
                  </a-col>
                  <a-col :span="12">
                    <div class="proposal-info">
                      <span class="label">创建时间:</span>
                      <span>{{ formatTimestamp(item.createdAt) }}</span>
                    </div>
                  </a-col>
                </a-row>
                
                <!-- 投票进度 -->
                <div style="margin-top: 16px">
                  <div style="display: flex; justify-content: space-between; margin-bottom: 8px">
                    <span>赞成: {{ item.votesFor }} 票</span>
                    <span>反对: {{ item.votesAgainst}} 票</span>
                  </div>
                  <a-progress
                    :percent="getVoteProgress(item)"
                    :status="item.status === 'passed' ? 'success' : 'active'"
                  />
                </div>
                
                <!-- 投票按钮 -->
                <div v-if="item.status === 'pending'" style="margin-top: 16px; text-align: right">
                  <a-space>
                    <a-button
                      type="primary"
                      @click="confirmVote(item, true)"
                      :loading="isVoting"
                    >
                      <CheckOutlined /> 赞成
                    </a-button>
                    <a-button
                      danger
                      @click="confirmVote(item, false)"
                      :loading="isVoting"
                    >
                      <CloseOutlined /> 反对
                    </a-button>
                  </a-space>
                </div>
              </a-card>
            </a-list-item>
          </template>
        </a-list>
      </a-spin>
    </a-card>

    <!-- 创建提案模态框 -->
    <a-modal
      v-model:open="createProposalModalVisible"
      title="创建提案"
      :confirm-loading="isCreatingProposal"
      @ok="createProposal"
      width="700px"
    >
      <a-form :model="proposalForm" layout="vertical">
        <a-form-item label="家族 ID" required>
          <a-input
            v-model:value="proposalForm.familyId"
            placeholder="请输入家族 ID (0x...)"
            size="large"
          />
        </a-form-item>

        <a-form-item label="提案标题" required>
          <a-input
            v-model:value="proposalForm.title"
            placeholder="请输入提案标题"
            size="large"
            :maxlength="100"
            show-count
          />
        </a-form-item>

        <a-form-item label="提案描述" required>
          <a-textarea
            v-model:value="proposalForm.description"
            placeholder="请详细描述提案内容"
            :rows="6"
            :maxlength="1000"
            show-count
          />
        </a-form-item>

        <a-form-item label="提案类型">
          <a-select
            v-model:value="proposalForm.proposalType"
            size="large"
            :options="proposalTypes"
          />
        </a-form-item>

        <a-alert
          type="info"
          message="投票规则"
          description="提案创建后，家族成员可以进行投票。赞成票超过半数即可通过。"
          show-icon
        />
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped lang="scss">
.governance {
  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24px;
    margin-bottom: 24px;
    background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
    border-radius: 12px;
    color: white;
    
    .header-content {
      h2 {
        margin: 0 0 8px;
        font-size: 28px;
        color: white;
      }
      
      p {
        margin: 0;
        font-size: 14px;
        opacity: 0.9;
      }
    }
  }
  
  .proposal-info {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .label {
      font-weight: 500;
      color: #666;
    }
  }
}
</style>

